﻿using BCCommon;
using BCData.TMS.User.UserAddressBook;
using BCDto.TMS.User.UserAddressBook;
using BCDto.Website.User;
using BCEntity.TMS.User.UserAddressBook;
using BCService.Common.Area;
using BCService.Utils;
using System;
using System.Collections.Generic;

namespace BCService.TMS.User.UserAddressBook
{
    public class UserAddressBookService : IUserAddressBookService
    {
        #region var
        private readonly IDatabaseContext databaseContext;
        private readonly IUserAddressBookData userAddressBookData;
        private readonly IZoneService zoneService;

        #endregion

        #region 构造函数
        public UserAddressBookService(IUserAddressBookData userAddressBookData, 
            IDatabaseContext databaseContext,
            IZoneService zoneService)
        {
            this.userAddressBookData = userAddressBookData;
            this.databaseContext = databaseContext;
            this.zoneService = zoneService;
        }
        #endregion

        #region Add
        /// <summary>
        /// 添加新用户地址薄纪录
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <param name="userAddressBookRequestDto">用户地址薄添加信息</param>
        /// <returns></returns>
        public UserAddressBookDto Add(UserAddressBookRequestDto userAddressBookRequestDto, UserDto user)
        {
            if (string.IsNullOrWhiteSpace(userAddressBookRequestDto.ProvinceCode) && string.IsNullOrWhiteSpace(userAddressBookRequestDto.CityCode) && string.IsNullOrWhiteSpace(userAddressBookRequestDto.CountyCode))
            {
                throw new ArgumentException("省市区信息不能为空");
            }
            var zoneEntity = this.zoneService.GetFromZoneEntity(userAddressBookRequestDto.CountyCode);
            if (zoneEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("区县编码不存在!");
            }
            databaseContext.BeginTransaction();
            if (userAddressBookRequestDto.IsDefault)
            {
                //更新此用户其他地址薄记录是否默认为false
                this.userAddressBookData.UpdateIsDefault(user.UserId).GetAwaiter().GetResult();
            }
            var result = this.userAddressBookData.InsertAsync(new UserAddressBookEntity() 
            {
                UserId = user.UserId,
                ContactName = userAddressBookRequestDto.ContactName,
                ContactPhone = userAddressBookRequestDto.ContactPhone,
                ProvinceCode = userAddressBookRequestDto.ProvinceCode,
                CityCode = userAddressBookRequestDto.CityCode,
                CountyCode = userAddressBookRequestDto.CountyCode,
                Address = userAddressBookRequestDto.Address,
                Longitude = userAddressBookRequestDto.Longitude,
                Latitude = userAddressBookRequestDto.Latitude,
                IsDefault = userAddressBookRequestDto.IsDefault,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            }).GetAwaiter().GetResult();
            databaseContext.Commit();
            return result.As<UserAddressBookDto>();
        }
        #endregion

        #region update
        /// <summary>
        /// 修改用户地址薄记录
        /// </summary>
        /// <param name="userAddressBookRequestDto">用户地址薄信息</param>
        /// <param name="userAddressBookId">用户地址薄Id</param>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        public UserAddressBookDto Update(UserAddressBookRequestDto userAddressBookRequestDto, long userAddressBookId, UserDto user)
        {
            var result = this.userAddressBookData.GetEntityAsync(userAddressBookId).Result;
            if (result == null)
            {
                throw new ArgumentException("用户地址薄信息不存在");
            }
            if (result.UserId != user.UserId)
            {
                throw new ArgumentException("此信息不归属您，无权限修改");
            }
            if (string.IsNullOrWhiteSpace(userAddressBookRequestDto.ProvinceCode) && string.IsNullOrWhiteSpace(userAddressBookRequestDto.CityCode) && string.IsNullOrWhiteSpace(userAddressBookRequestDto.CountyCode))
            {
                throw new ArgumentException("省市区信息不能为空");
            }
            var zoneEntity = this.zoneService.GetFromZoneEntity(userAddressBookRequestDto.CountyCode);
            if (zoneEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("区县编码不存在!");
            }
            result.ContactName = userAddressBookRequestDto.ContactName;
            result.ContactPhone = userAddressBookRequestDto.ContactPhone;
            result.ProvinceCode = userAddressBookRequestDto.ProvinceCode;
            result.CityCode = userAddressBookRequestDto.CityCode;
            result.CountyCode = userAddressBookRequestDto.CountyCode;
            result.Address = userAddressBookRequestDto.Address;
            result.Longitude = userAddressBookRequestDto.Longitude;
            result.Latitude = userAddressBookRequestDto.Latitude;
            result.IsDefault = userAddressBookRequestDto.IsDefault;
            result.UpdateTime = DateTime.Now;
            databaseContext.BeginTransaction();
            if (userAddressBookRequestDto.IsDefault)
            {
                //更新此用户其他地址薄记录是否默认为false
                this.userAddressBookData.UpdateIsDefault(user.UserId).GetAwaiter().GetResult();
            }
            this.userAddressBookData.UpdateAsync(result).GetAwaiter().GetResult();
            databaseContext.Commit();
            return result.As<UserAddressBookDto>();
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除用户地址薄记录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="userAddressBookId"></param>
        /// <returns></returns>
        public void Delete(UserDto user, long userAddressBookId)
        {
            var result = this.userAddressBookData.GetEntityAsync(userAddressBookId).Result;
            if (result == null)
            {
                throw new ArgumentException("用户地址薄信息不存在");
            }
            if (result.UserId != user.UserId)
            {
                throw new ArgumentException("此信息不归属您，无权限删除");
            }
            this.userAddressBookData.DeleteAsync(userAddressBookId).GetAwaiter().GetResult();
        }
        #endregion

        #region GetByUserAddressBookId
        /// <summary>
        /// 获取用户地址薄记录
        /// </summary>
        /// <param name="userAddressBookId">用户地址薄Id</param>
        /// <returns></returns>
        public UserAddressBookViewDto GetById(long userAddressBookId)
        {
            var result = userAddressBookData.GetEntityAsync(userAddressBookId).Result;
            return result.As<UserAddressBookViewDto>();
        }
        #endregion

        public PageableList<UserAddressBookViewDto> Query(UserDto user, int pageIndex, int pageSize)
        {
            var (data, dataCount) = this.userAddressBookData.Query(user.UserId, pageIndex, pageSize).Result;
            return new PageableList<UserAddressBookViewDto>()
            {
                Count = dataCount,
                Items = data.As<List<UserAddressBookViewDto>>(),
                PageIndex = pageIndex,
                PageSize = pageSize
            };
        }

        public IEnumerable<UserAddressBookViewDto> GetList(UserDto user)
        {
            var result = this.userAddressBookData.GetList(user.UserId).Result;
            return result.As<IEnumerable<UserAddressBookViewDto>>();
        }
    }
}
